'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
from dopplershift.collector.backends.auth.default import DefaultAuthBackend
from twisted.internet import reactor, protocol
from twisted.protocols.memcache import MemCacheProtocol, DEFAULT_PORT

class MemcachedAuthBackend(DefaultAuthBackend):
    _connected = False 
    protocol = MemCacheProtocol
    def __init__(self, host='localhost', port=11211, on=True, **kwargs):
        DefaultAuthBackend.__init__(host, port, on)
    def _getUserSession(self, result, event_handler):
        if not result[1]:
            return self._generate(event_handler, False)
        d = self._proto.get(result[1])
        d.addCallback(self._getAuthInfo, event_handler)
        d.addErrback(self._fail, event_handler)
    def _getAuthInfo(self, result, event_handler):
        self._generate(event_handler, result[1])
    
'''
class MemcachedAuthBackend(DefaultAuthBackend):
    _client = None
    def getClient(self):
        return protocol.ClientCreator(reactor, MemCacheProtocol).connectTCP("localhost", DEFAULT_PORT)
        #return self._client
    def isAuth(self, session_id, event_handler):
        d = self.getClient()
        d.addCallback(self._memcachedConnect, session_id, event_handler)
        d.addErrback(self._memcachedConnectFailed, event_handler)
        print "AUTHKEY", session_id
    def _memcachedConnectFailed(self, err, event_handler):
        event_handler.generate("AuthResponse", False)
        print "CONNECT FAILD"
    def _memcachedConnect(self, proto, session_id, event_handler):
        d = proto.get(session_id)
        d.addCallback(self._authResponse, proto, event_handler)
        d.addErrback(self._authFail, event_handler)
    def _authResponse(self, result, proto, event_handler):
        print "AUTH RESPONSE", result
        d = proto.get(result[1])
        d.addCallback(self._authUser, event_handler)
        d.addErrback(self._authFail, event_handler)
        
    def _authUser(self, result, event_handler):
        print "AUTH USER", result[1]
        event_handler.generate("AuthResponse", result[1])
    def _authFail(self, err, event_handler):
        print err
        event_handler.generate("AuthResponse", False)
'''